
package com.fx.apartment.modules.activity.wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fx.apartment.modules.activity.entity.Activity;
import com.fx.apartment.modules.activity.entity.ActivityParticipation;
import com.fx.apartment.modules.activity.service.IActivityParticipationService;
import com.fx.apartment.modules.activity.vo.ActivityParticipationVO;
import com.fx.apartment.modules.activity.vo.ActivityVO;
import com.fx.apartment.common.support.BaseEntityWrapper;
import com.fx.apartment.common.tool.utils.BeanUtil;
import com.fx.apartment.common.tool.utils.Func;
import com.fx.apartment.common.tool.utils.SpringUtil;
import com.google.common.collect.Lists;

import java.util.List;
import java.util.Objects;

/**
 * 活动设置包装类,返回视图层所需的字段
 *
 * @author QinXueFeng
 * @since 2021-04-19
 */
public class ActivityWrapper extends BaseEntityWrapper<Activity, ActivityVO> {

	private static final IActivityParticipationService activityParticipationService;

	static {
		activityParticipationService = SpringUtil.getBean(IActivityParticipationService.class);
	}
	public static ActivityWrapper build() {
		return new ActivityWrapper();
 	}

	@Override
	public ActivityVO entityVO(Activity activity) {
		ActivityVO activityVO = Objects.requireNonNull(BeanUtil.copy(activity, ActivityVO.class));
		//TODO 用户ID
		List<ActivityParticipation> list = activityParticipationService.list(Wrappers.<ActivityParticipation>lambdaQuery().eq(ActivityParticipation::getActivityId, activityVO.getId()).orderByDesc(ActivityParticipation::getVotesNum));
		List<ActivityParticipationVO> list1 = Lists.newArrayListWithCapacity(list.size());
		int num=0;
		for (int i = 0; i < list.size(); i++) {
			ActivityParticipationVO participationVO = BeanUtil.copy(list.get(i), ActivityParticipationVO.class);
			participationVO.setRank(i+1);
			if("".equals(participationVO.getCreateUser())){
				num=i;
			}
			list1.add(participationVO);
		}
		if(1==activityVO.getStatus()){
			ActivityParticipationVO activityParticipationVO = list1.get(num);
			list1.remove(num);
			list1.add(0,activityParticipationVO);
		}
		if(Func.isNotEmpty(list1)){
			int sum = list1.stream().mapToInt(ActivityParticipation::getVotesNum).sum();
			activityVO.setTotalVotes(sum);
			activityVO.setParticipants(list1.size());
			activityVO.setActivityParticipationList(list1);
		}
		//User createUser = UserCache.getUser(activity.getCreateUser());
		//User updateUser = UserCache.getUser(activity.getUpdateUser());
		//activityVO.setCreateUserName(createUser.getName());
		//activityVO.setUpdateUserName(updateUser.getName());

		return activityVO;
	}


}
